using MongoDB.Bson;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.Entities.ScreeningTool
{
    public static class ResearchProductsExtensions
    {
        public static ResearchState GetResearchState(this IEnumerable<ResearchProduct> researchProducts, BsonDocument source)
            => researchProducts.GetResearchState(source.GetResearchStates());

        public static ResearchState GetResearchState(this IEnumerable<ResearchProduct> researchProducts, ResearchStates researchStates)
        {
            if (researchProducts == null || !researchProducts.Any())
                return ResearchState.ResearchAvailable;

            var map = researchStates.MapToResearchProducts();
            var query = researchProducts
                .Where(researchProduct => map.ContainsKey(researchProduct))
                .Select(researchProduct => map[researchProduct])
                .Where(researchState => researchState != ResearchState.ResearchNotAvailable);

            if (query.Count() >= 2)
            {
                if (query.All(researchState => researchState == ResearchState.FrameworkNotApplicable))
                    return ResearchState.FrameworkNotApplicable;

                throw new InvalidOperationException("Cannot have more than one research state different from ResearchNotAvailable.");
            }

            return query.Any() ? query.Single() : ResearchState.ResearchNotAvailable;
        }
    }
}
